package yunquan.wang.base.spring.security;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.annotations.Cache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import yunquan.wang.modules.base.dao.RolesAuthorityDao;
import yunquan.wang.modules.base.entity.GroupInfo;
import yunquan.wang.modules.base.entity.RolesAuthority;
import yunquan.wang.modules.base.entity.UserBasic;
import yunquan.wang.modules.base.service.GroupInfoService;
import yunquan.wang.modules.base.service.UserBasicService;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Service
@Transactional(value = "jpaTransaction")
public class SecurityService {
	@Resource
	private RolesAuthorityDao rolesAuthorityDao;
	@Resource
	private GroupInfoService groupInfoService;
	@Resource
	private UserBasicService userBasicService;
	/**
	 * 加入到缓存中
	 * @param rolesId
	 * @return
	 */
    @Cacheable(value="securityCache", key="#rolesId + 'securityCache'")
	public Set<GrantedAuthority> getRoleAuthority(String rolesId) {
		Set<GrantedAuthority> gaSet = new HashSet<GrantedAuthority>();
		List<RolesAuthority> raList = rolesAuthorityDao
				.findByRolesinfoId(rolesId);
		for (RolesAuthority ra : raList) {
			GrantedAuthorityRulesImpl impl = new GrantedAuthorityRulesImpl(ra
					.getAuthority().getName());
			impl.setRulesInfo(ra.getRulesInfos());
			gaSet.add(impl);
		}
		return gaSet;
	}
 
	public List<String> getAllGroupNames() {
		List<GroupInfo> allGroups = groupInfoService.findAll();
		List<String> groupIds = Lists.newArrayList();
		for (GroupInfo groupInfo : allGroups) {
			groupIds.add(groupInfo.getGroupName());
		}
		return groupIds;
	}

	/**
	 * 获取到用户所属的用户组
	 * @return
	 */
	public Map<String, List<String>> getAllUserGroups() {
		List<UserBasic> users = userBasicService.findAll();
		Map<String, List<String>> map = Maps.newHashMap();
		for (UserBasic user : users) {
			List<String> groups = Lists.newArrayList();
			groups = getAllGroups(groups, user.getGroupInfo());
			map.put(user.getLoginName(), groups);
		}
		return map;

	}

	private List<String> getAllGroups(List<String> list, GroupInfo info) {
		if (info != null) {
			list.add(info.getGroupName());
		}
		List<GroupInfo> groups = info.getChilds();
		if (groups.size() != 0) {
			for (GroupInfo entity : groups) {
				getAllGroups(list, entity);
			}
		}
		return list;

	}
}
